<?php

include_once ('../../utilities.php')

?>
<!DOCTYPE html>
<html>
<head>
	<link rel="stylesheet" type="text/css" href="../../reset.css">
	<link rel="stylesheet" type="text/css" href="../../mainStyle.css">
	<link rel="stylesheet" type="text/css" href="../../searchButton.css">
	<title>Email Change</title>
</head>
<body>

	<div id="container">
		<?php

$root = '../../';
include_once ('../../header.php')

?>
        
		<div id="page-body">
		<?php

if (!empty($_FILES['photo']['tmp_name']) && !empty($_FILES['photo']['name']) &&
    !empty($_SESSION['LoggedIn']) && !empty($_SESSION['User']))
{
    //If form was filled out
    $user = unserialize($_SESSION['User']);
    if (checkPhoto())
    {
        //Photo is png, jpg or gif
        //Prep photo for database
        $filename = mysqli_real_escape_string($mysqli, $_FILES['photo']['name']);
        $photo = file_get_contents($_FILES['photo']['tmp_name']);
        $photo = mysqli_real_escape_string($mysqli, $photo);
        $ext = mysqli_real_escape_string($mysqli, pathinfo($_FILES['photo']['name'],
            PATHINFO_EXTENSION));
        //Insert photo to database
        $query = "INSERT INTO Uploads (FileName,FileType,FileData,ChapterId) VALUES('" .
            $filename . "', '" . $ext . "', '" . $photo . "', '" . $user->getChapter()->
            getChapterId() . "')";
        $mysqli->query($query);
        $query = "SELECT * FROM Uploads WHERE FileName = '" . $filename . "'";
        $data = $mysqli->query($query);
        if ($data->num_rows != 0)
        {
            //Update user's picture id
            $row = $data->fetch_array(MYSQLI_ASSOC);
            $user->setPictureId($row['FileID']);
            $_SESSION['User'] = serialize($user);
        }

?>
					<p>Your photo has been changed. Please <a href="../">click here to return to your account page</a>.</p>
					<?php

    } else
    {

?>
					<p>Sorry, the phototype was invalid. Please <a href="./">click here to try again</a>.</p>
					<?php

    }
} elseif (!empty($_SESSION['LoggedIn']) && !empty($_SESSION['User']))
{
    //Form to upload the photo
    $user = unserialize($_SESSION['User']);

?>
				
				<p>Please upload a photo. It must be a png, gif or jpg.</p>
				
				<form action="./" method="post" enctype="multipart/form-data">
				<fieldset>
				<label for="photo">Photo: </label>
				<input type="file" name="photo" id="photo"/><br />
				<br />
				<input type="submit" value="Upload File" />
				</fieldset>
				</form>
				
				<?php

} else
{

?>
					
			   <p>You must login to view this page.</p>
									
			   <?php

}

?>
		</div>
		
		<?php

include_once ('../../footer.php')

?>
	</div>

</body>
</html>